<?php
/**
 * 店铺列表
 *
 * by 33h ao.c om 好商 城
*/

defined('In33hao') or exit('Access Invalid!');

class store_listControl extends BaseHomeControl {
	/**
	 * 店铺列表
	 */
	public function indexOp(){
		//读取语言包
		Language::read('home_store_class_index');	
		$lang	= Language::getLangContent();
        Tpl::output("index_sign",'store');
		//店铺类目快速搜索
		$class_list = ($h = F('store_class')) ? $h : rkcache('store_class',true,'file');
		if (!key_exists($_GET['cate_id'],$class_list)) $_GET['cate_id'] = 0;
		Tpl::output('class_list',$class_list);

		//店铺搜索
		$model = Model();
		$condition = array();
		$keyword = trim($_GET['keyword']);
		$condition['store_class'] = 1;
		if(C('fullindexer.open') && !empty($keyword)){
			//全文搜索
			$condition = $this->full_search($keyword);
		}else{
			if ($keyword != ''){
				$condition['store_name|store_zy'] = array('like','%'.$keyword.'%');
			}
			
			if ($_GET['user_name'] != ''){
				$condition['member_name'] = trim($_GET['user_name']);
			}
		}
		if (!empty($_GET['area_info'])){
			$tabs = preg_split("#\s+#", $_GET['area_info'], -1, PREG_SPLIT_NO_EMPTY);
			$len=count($tabs);
			$area_name=$tabs[$len-1];
			if($area_name)
			{
				$area_name=trim($area_name);
				$condition['area_info'] = array('like','%'.$area_name.'%');
			}
		}
		if ($_GET['cate_id'] > 0){
			$child = array_merge((array)$class_list[$_GET['cate_id']]['child'],array($_GET['cate_id']));
			$condition['sc_id'] = array('in',$child);
		}

		$condition['store_state'] = 1;

		if (!in_array($_GET['order'],array('desc','asc'))){
			unset($_GET['order']);
		}
		if (!in_array($_GET['key'],array('store_sales','store_credit'))){
			unset($_GET['key']);
		}

		$order = 'store_sort asc';

        if (isset($condition['store.store_id'])){
            $condition['store_id'] = $condition['store.store_id'];unset($condition['store.store_id']);
        }
        
        $model_store = Model('store');
        $store_list = $model_store->where($condition)->order($order)->page(10)->select();
        //获取店铺商品数，推荐商品列表等信息
        $store_list = $model_store->getStoreSearchList($store_list);

        //print_r($store_list);exit();
        //信用度排序
        if($_GET['key'] == 'store_credit') {
            if($_GET['order'] == 'desc') {
                $store_list = sortClass::sortArrayDesc($store_list, 'store_credit_average');
            }else {
                $store_list = sortClass::sortArrayAsc($store_list, 'store_credit_average');
            }
        }else if($_GET['key'] == 'store_sales') {//销量排行
            if($_GET['order'] == 'desc') {
                $store_list = sortClass::sortArrayDesc($store_list, 'num_sales_jq');
            }else {
                $store_list = sortClass::sortArrayAsc($store_list, 'num_sales_jq');
            }
        }
		Tpl::output('store_list',$store_list);
		
		Tpl::output('show_page',$model->showpage(2));
		// 页面输出
		Tpl::output('index_sign','store_list');
		//当前位置
		if (intval($_GET['cate_id']) > 0){
			$nav_link[1]['link'] = 'index.php?act=shop_search';
			$nav_link[1]['title'] = $lang['site_search_store'];
			$nav =$class_list[$_GET['cate_id']];
			//如果有父级
			if ($nav['sc_parent_id'] > 0){
				$tmp = $class_list[$nav['sc_parent_id']];
				//存入父级
				$nav_link[] = array(
					'title'=>$tmp['sc_name'],
					'link'=>"index.php?act=store_list&cate_id=".$nav['sc_parent_id']
				);
			}
			//存入当前级
			$nav_link[] = array(
				'title'=>$nav['sc_name']
			);
		}else{
			$nav_link[1]['link'] = 'index.php';
			$nav_link[1]['title'] = $lang['homepage'];
			$nav_link[2]['title'] = $lang['site_search_store'];
		}

		$purl = $this->getParam();
		Tpl::output('nav_link_list',$nav_link);
		Tpl::output('purl', urlShop($purl['act'], $purl['op'], $purl['param']));

		//SEO
		Model('seo')->type('index')->show();
		Tpl::output('html_title',(empty($_GET['keyword']) ? '' : $_GET['keyword'].' - ').C('site_name').$lang['nc_common_search']);
		
        Tpl::showpage('store_list');
	}

	//
 	public function checkIsSqStoreOp(){

		 $store_id = $_GET['store_id'];
		 $_SESSION['myStoreid'] = $store_id;
		 $condition['store_id'] = $store_id;
		 $store_info = Model('store')->getStoreInfo($condition);
		 if($store_info['store_class']==1){
			  echo 1;
		 }else{
			  echo 0;
		 }
	}

	//查找店铺
	public function search_stroeOp(){
		$store_model = Model('store');
		$where['is_own_shop'] = 0;
		$where['store_class'] = ['in','0,1'];
		$store_list = $store_model->getStoreOnlineList($where,'','','store_name,store_letters,store_id');
		$order_sec = array("A","B",'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
		$FormatList = array();
		foreach($order_sec as $k => $v){
			foreach($store_list as $value){
				$sub = strtoupper(substr($value['store_letters'],0,1));
				if($v==$sub){
					$FormatList[$v][] = $value;
				}
			}
		}
		$key = $_POST['key'];
		$condition['store_letters'] = array("like","%".$key."%");
		$keydata = $store_model->getStoreOnlineList($condition,1);

		$html = '<div class=\'search_store\' ><a href="javascript:;" store_id="1">自营店铺</a></div>';
		$key = 0;
		foreach ($FormatList as $k => $item) {
			$html .=" <div class='list_item'><div class=\"list_key\">".$k."</div><div class=\"list\">";
			foreach($item as $v){
				if($v['store_id']==$keydata[0]['store_id']){
					$line = $key;
					$html .= '<a href="javascript:void(0)" class="searchNow" store_id=' . $v['store_id'] . '>' . $v['store_name'] . '</a>';
				}else {
					$html .= '<a href="javascript:void(0)" store_id=' . $v['store_id'] . '>' . $v['store_name'] . '</a>';
				}
			}
			$html .= " </div></div>" ;
			$key++;
		}
		$array = array(
				"data" => $html,
				"key" => $line,
		);
		echo json_encode($array);
	}

	//查找店铺
	public function search_supplierOp(){
		$store_model = Model('store');
		$where['is_own_shop'] = 0;
		$where['store_class'] = 3;
		$store_list = $store_model->getStoreOnlineList($where,'','','store_name,store_letters,store_id');
		$order_sec = array("A","B",'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
		$FormatList = array();
		foreach($order_sec as $k => $v){
			foreach($store_list as $value){
				$sub = strtoupper(substr($value['store_letters'],0,1));
				if($v==$sub){
					$FormatList[$v][] = $value;
				}
			}
		}
		$key = $_POST['key'];
		$condition['store_letters'] = array("like","%".$key."%");
		$keydata = $store_model->getStoreOnlineList($condition,1);
        $html = '';
		$key = 0;
		foreach ($FormatList as $k => $item) {
			$html .=" <div class='list_item'><div class=\"list_key\">".$k."</div><div class=\"list\">";
			foreach($item as $v){
				if($v['store_id']==$keydata[0]['store_id']){
					$line = $key;
					$html .= '<a href="javascript:void(0)" class="searchNow" store_id=' . $v['store_id'] . '>' . $v['store_name'] . '</a>';
				}else {
					$html .= '<a href="javascript:void(0)" store_id=' . $v['store_id'] . '>' . $v['store_name'] . '</a>';
				}
			}
			$html .= " </div></div>" ;
			$key++;
		}
		$array = array(
				"data" => $html,
				"key" => $line,
		);
		echo json_encode($array);
	}

	/**
	 * 异步ajax请求 返回店铺名称
	 */
	Public function findStoreByLettersOp(){
		  $store_letters = $_POST['letters'];
		  $condition['store_letters'] = $store_letters;
		  $condition['store_class'] = ['in','0,1'];
		  $store_model = Model("store");
		  $storeDate = $store_model->getStoreInfo($condition);
		  print_r(json_encode($storeDate));
	}

	/**
	 * 异步ajax请求 返回店铺名称
	 */
	Public function findSupplierByLettersOp(){
		$store_letters = $_POST['letters'];
		$condition['store_letters'] = $store_letters;
		$condition['store_class'] = 3;
		$store_model = Model("store");
		$storeDate = $store_model->getStoreInfo($condition);
		print_r(json_encode($storeDate));
	}

	/**
	 * 全文搜索
	 *
	 */
	private function full_search($search_txt){
		$conf = C('fullindexer');
		import('libraries.sphinx');
		$cl = new SphinxClient();
		$cl->SetServer($conf['host'], $conf['port']);
		$cl->SetConnectTimeout(1);
		$cl->SetArrayResult(true);
		$cl->SetRankingMode($conf['rankingmode']?$conf['rankingmode']:0);
		$cl->setLimits(0,$conf['querylimit']);
	
		$matchmode = $conf['matchmode'];
		$cl->setMatchMode($matchmode);
		$res = $cl->Query($search_txt, $conf['index_shop']);
		if ($res){
			if (is_array($res['matches'])){
				foreach ($res['matches'] as $value) {
					$matchs_id[] = $value['id'];
				}
			}
		}
		if ($search_txt != ''){
			$condition['store.store_id'] = array('in',$matchs_id);
		}
		return $condition;
	}
	
	function getParam() {
	    $param = $_GET;
	    $purl = array();
	    $purl['act'] = $param['act'];
	    unset($param['act']);
	    $purl['op'] = $param['op'];
	    unset($param['op']); unset($param['curpage']);
	    $purl['param'] = $param;
	    return $purl;
	}
}

class sortClass{
	//升序
	public static function sortArrayAsc($preData,$sortType='store_sort'){
		$sortData = array();
		foreach ($preData as $key_i => $value_i){
			$price_i = $value_i[$sortType];
			$min_key = '';
			$sort_total = count($sortData);
			foreach ($sortData as $key_j => $value_j){
				if($price_i<$value_j[$sortType]){
					$min_key = $key_j+1;
					break;
				}
			}
			if(empty($min_key)){
				array_push($sortData, $value_i);
			}else {
				$sortData1 = array_slice($sortData, 0,$min_key-1);
				array_push($sortData1, $value_i);
				if(($min_key-1)<$sort_total){
					$sortData2 = array_slice($sortData, $min_key-1);
					foreach ($sortData2 as $value){
						array_push($sortData1, $value);
					}
				}
				$sortData = $sortData1;
			}
		}
		return $sortData;
	}
	//降序
	public static function sortArrayDesc($preData,$sortType='store_sort'){
		$sortData = array();
		foreach ($preData as $key_i => $value_i){
			$price_i = $value_i[$sortType];
			$min_key = '';
			$sort_total = count($sortData);
			foreach ($sortData as $key_j => $value_j){
				if($price_i>$value_j[$sortType]){
					$min_key = $key_j+1;
					break;
				}
			}
			if(empty($min_key)){
				array_push($sortData, $value_i);
			}else {
				$sortData1 = array_slice($sortData, 0,$min_key-1);
				array_push($sortData1, $value_i);
				if(($min_key-1)<$sort_total){
					$sortData2 = array_slice($sortData, $min_key-1);
					foreach ($sortData2 as $value){
						array_push($sortData1, $value);
					}
				}
				$sortData = $sortData1;
			}
		}
		return $sortData;
	}
}
